<template>
	<div class="qrcode">
		<div id="reader"></div>
	</div>
</template>

<script>
	import { Html5Qrcode } from "html5-qrcode";
	export default {
		data() {
			return {
				cameraId: ""
			}
		},
		created() {
			// #ifndef H5
			this.doScan();
			// #endif
			
			// #ifdef H5
			this.getCameras();
			// #endif
			
		},
		beforeDestroy() {
			this.stop();
		},
		methods: {
			processScan(code){	
				let prefix = code.substr(0,6).toLowerCase();
				if(prefix == 'http:/' || prefix == 'https:'){
					uni.showModal({
						title: '扫描结果',
						content: code,
						confirmText:'复制',
						success: function (res) {
							if (res.confirm) {
								uni.setClipboardData({
									data: code
								});
							} 
						}
					});
					this.goto(code);
				}else if(prefix == 'asset:'){
					uni.redirectTo({
						url: '/pages/asset/view/info?id='+code.substr(8)
					});
				}else if(prefix == 'use://'){
					uni.redirectTo({
						url: '/pages/asset/out/use?id='+code.substr(6)
					});
				}else if(prefix == 'pur://'){
					uni.redirectTo({
						url: '/pages/asset/in/purchase?id='+code.substr(6)
					});
				}else{
					uni.redirectTo({
						url: '/pages/asset/view/info?num='+code
					});
				}
			},
			
			doScan(field){
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function (res) {
						this.processScan(res.result);
					}
				});
			},
			getCameras() {
				Html5Qrcode.getCameras().then((devices) => {
					console.log(devices)
					if (devices && devices.length) {
						this.html5QrCode = new Html5Qrcode("reader");
						if (devices.length > 1) {
							this.cameraId = devices[1].id;
						} else {
							this.cameraId = devices[0].id;
						}
						this.start();
					} else {
						uni.showToast({
							title: '没有摄像机',
							duration: 2000
						});
					}
				})
				.catch((err) => {
					this.$modal.msgError("您需要授予相机访问权限");
					this.html5QrCode = new Html5Qrcode("reader");
				});
			},
			start() {
				//environment后置 user前置
				this.html5QrCode.start(
						this.cameraId, {
							fps: 2,
							qrbox: {
								width: 250,
								height: 250
							},
						},
						(decodedText, decodedResult) => {
							this.processScan(decodedText);
						}
					)
					.catch((err) => {
						this.$modal.msgError(err);
					});
			},
			stop() {
				this.html5QrCode.stop().then((ignore) => {
						console.log("QR Code scanning stopped.");
					})
					.catch((err) => {
						// Stop failed, handle it.
						console.log("Unable to stop scanning.");
					});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.qrcode {
		position: fixed;
		height: 100%;
		width: 100%;
		background: rgba(0, 0, 0, 1);
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: 10009;
	}

	#reader {
		top: 50%;
		left: 0;
		transform: translateY(-50%);
	}
</style>